package com.game.springbootstart.controller.user;

import com.game.springbootstart.VO.ChangePasswordRequest;
import com.game.springbootstart.config.Result;
import com.game.springbootstart.entity.Admin;
import com.game.springbootstart.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IAdminService adminService;

    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {
        String currentUsername = changePasswordRequest.getUserName();
        Admin admin = adminService.getAdminByUsername(currentUsername);

        if (admin == null) {
            return Result.fail();
        }
        if(!admin.getPassword().equals(DigestUtils.md5DigestAsHex(changePasswordRequest.getOldPassword().getBytes()) )){
            return Result.fail();
        }


        // 更新新密码
        String newPassword = changePasswordRequest.getNewPassword();
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        admin.setPassword(newPassword);
        adminService.updateById(admin);

        return Result.success("密码修改成功");
    }

    @PostMapping("/saveOrMod")
    public Result saveOrUpdate(@RequestBody Admin admin) {
        if (admin.getId() == null) {
            return Result.success(adminService.updateById(admin));
        }
        return Result.success(adminService.updateById(admin));
    }

    @PostMapping("/insertImg")
    public Result insertImg(@RequestBody Admin admin) {
        Boolean flag = adminService.updateById(admin);
        if (flag) {
            return Result.success(flag);
        } else {
            return Result.fail();
        }
    }

    @GetMapping("/list")
    public Result listByName(@RequestParam Long id){
        return Result.success(adminService.listById(id));
    }
}
